/*
 * @Description: 
 * @Author: 梁萌
 * @Date: 2020-12-13 10:47:25
 * @LastEditTime: 2020-12-15 07:28:02
 * @FilePath: \koa_server\service\web_socket_service.js
 */

//引入ws包
const WebSocket = require('ws');
const path = require('path');
const fileUtils = require('../utils/file_utils');

//创建WebSoctet.Server对象
const wss = new WebSocket.Server({
    port: 1111
});

//服务端开启监听
module.exports.listen = () => {
    //对客户端连接事件进行监听
    //client 客户端的连接soctet对象
    wss.on('connection', client => {
        console.log("有客户端连接成功");
        //对客户端的message事件进行监听
        //msg 客户端发送给服务端的数据
        client.on('message', async msg => {
            console.log("客户端发送数据给服务端了,数据是:" + msg);
            //对客户端传递过来的数据进行处理
            let payload = JSON.parse(msg);
            const action = payload.action;
            if (action === 'getData') {
                let filePath = '../data/' + payload.chartName + '.json'; //拼接文件路径
                filePath = path.join(__dirname, filePath); //获取文件绝对路径
                const ret = await fileUtils.getFileJsonData(filePath); //读取到的文件内容
                payload.data = ret;
                client.send(JSON.stringify(payload)); //将json对象转为json字符串,返回到前端
            } else {
                //将前端发送过来的数据原封不动转发给所有连接状态的客户端
                wss.clients.forEach(client => {
                    client.send(msg);
                });
            }
        });
    });
}